package org.gnyxy.service.impl;

import cn.hutool.core.io.FileUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.gnyxy.context.BaseContext;
import org.gnyxy.dto.GenChartRequest;
import org.gnyxy.exception.BaseException;
import org.gnyxy.service.ChartService;
import org.gnyxy.service.ChatglmService;
import org.gnyxy.service.XfxhService;
import org.gnyxy.utils.ExcelUtils;
import org.gnyxy.vo.ChartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class ChartServiceImpl implements ChartService {
    private static final List<String> FILENAMES = Arrays.asList("xls", "xlsx", "csv", "XLS", "XLSX", "CSV");
    private static final long MAX_SIZE = 100 * 1025;
    @Autowired
    private XfxhService xfxhService;

    @Resource
    private ChatglmService chatglmService;
    /**
     * ai生成
     * @param multipartFile
     * @param chartRequest
     * @return
     */
    @Override
    public ChartVO generateResultByAI(MultipartFile multipartFile, GenChartRequest chartRequest) {
        String goal = chartRequest.getGoal();
        String chartType = chartRequest.getChartType();

        // 校验
        if (StringUtils.isBlank(goal)){
            throw new BaseException("目标为空");
        }
        // 获取大小并校验 不超过100KB
        long size = multipartFile.getSize();
        if (size > MAX_SIZE){
            throw new BaseException("文件超出限定大小");
        }
        // 获取原始名并进行校验
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        // 后缀名校验
        if (!FILENAMES.contains(suffix)){
            throw new BaseException("文件格式错误");
        }
        // 判断表格格式为xls、xlsx还是csv 并传入给相应的方法处理
        String value = null;
        // 校验数据格式
        switch (Objects.requireNonNull(suffix)) {
            case "xls":
            case "XLS":
                value = ExcelUtils.xlsToCsv(multipartFile);
                break;
            case "xlsx":
            case "XLSX":
                value = ExcelUtils.xlsxToCsv(multipartFile);
                break;
            case "csv":
            case "CSV":
                value = ExcelUtils.csvToString(multipartFile);
                break;
        }

//        String genResult;
//        String genChart;
//        try {
//            genResult = chatglmService.ExcelToResult(goal,value);
//            genChart = chatglmService.ExcelToJson(goal,value,chartType);
//        } catch (Exception e) {
//            throw new BaseException("AI异常");
//        }


        // 构建接入AI的预设
        StringBuilder builder = new StringBuilder();
        builder.append("分析需求:").append(goal).append("\n")
                .append("原始数据:\n").append(value).append("\n");
        String chartPrompt =
                builder +
                        "请你根据上述分析需求和原始csv数据直接写出前端的 Echarts V5 的 option 配置对象有效的JSON格式的代码，要求生成图表的类型为" +
                        chartType +
                        "，只需生成'option = {}'大括号里的文本内容，除了以上代码外不要生成任何多余的内容，不要输出任何多余的开头、结尾、注释\n"
                +"  \"title\": {\n" +
                        "    \"text\": \"调用成功率\"\n" +
                        "  },\n" +
                        "  \"tooltip\": {\n" +
                        "    \"trigger\": \"axis\",\n" +
                        "    \"axisPointer\": {\n" +
                        "      \"type\": \"shadow\"\n" +
                        "    }\n" +
                        "  },\n" +
                        "  \"legend\": {\n" +
                        "    \"data\": [\"调用成功量\", \"调用失败量\"]\n" +
                        "  },\n" +
                        "  \"grid\": {\n" +
                        "    \"left\": \"3%\",\n" +
                        "    \"right\": \"4%\",\n" +
                        "    \"bottom\": \"3%\",\n" +
                        "    \"containLabel\": true\n" +
                        "  },\n" +
                        "  \"xAxis\": {\n" +
                        "    \"type\": \"category\",\n" +
                        "    \"boundaryGap\": false,\n" +
                        "    \"data\": [\"2023-11-30\", \"2023-12-01\", \"2023-12-02\", \"2023-12-03\", \"2023-12-04\", \"2023-12-05\", \"2023-12-06\", \"2023-12-07\", \"2023-12-08\", \"2023-12-09\", \"2023-12-10\", \"2023-12-11\", \"2023-12-12\", \"2023-12-13\", \"2023-12-14\", \"2023-12-15\", \"2023-12-16\", \"2023-12-17\", \"2023-12-18\", \"2023-12-19\", \"2023-12-20\", \"2023-12-21\", \"2023-12-22\", \"2023-12-23\", \"2023-12-24\", \"2023-12-25\", \"2023-12-26\", \"2023-12-27\", \"2023-12-28\", \"2023-12-29\", \"2023-12-30\"]\n" +
                        "  },\n" +
                        "  \"yAxis\": {\n" +
                        "    \"type\": \"value\"\n" +
                        "  },\n" +
                        "  \"series\": [\n" +
                        "    {\n" +
                        "      \"name\": \"调用成功量\",\n" +
                        "      \"type\": \"bar\",\n" +
                        "      \"stack\": \"总量\",\n" +
                        "      \"data\": [0, 2449, 0, 16206, 0, 16814, 0, 0, 0, 0, 0, 0, 13439, 5814, 0, 12907, 22556, 43955, 0, 1064, 0, 0, 0, 0, 0]\n" +
                        "    },\n" +
                        "    {\n" +
                        "      \"name\": \"调用失败量\",\n" +
                        "      \"type\": \"bar\",\n" +
                        "      \"stack\": \"总量\",\n" +
                        "      \"data\": [0, 2449, 0, 16206, 0, 16814, 0, 0, 0, 0, 0, 0, 13439, 5814, 0, 12907, 22556, 43955, 0, 1064, 0, 0, 0, 0, 0]\n" +
                        "    }\n" +
                        "  ]\n" +
                        "}"
                ;

        String resultPrompt = builder +
                "请您根据提供的原始数据并结合分析需求，直接撰写一份简洁明了的数据分析报告。要求字数150字内，言简意赅。" +
                "请确保报告中只包含分析结果，不要包含任何前言、结尾或注释等附加内容。\n";

//         丢给AI生成
        String genChart = xfxhService.sendQuestion(chartPrompt);
        String genResult = xfxhService.sendQuestion(resultPrompt);
//         完成数据生成替换非法格式等
//        genChart = genChart.replace("option = ", "")
//                .replace("json", "")
//                .replace("```", "")
//                .trim();

        int start = genChart.indexOf('{');
        int end = genChart.lastIndexOf('}') + 1;
        genChart = genChart.substring(start, end).trim();


        genResult = genResult.trim();
        // 返回ChartVO
        return new ChartVO(genResult,genChart);
    }
}
